//
//  GYXTitleButton.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/3/7.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit

class GYXTitleButton: UIButton {

    
    /// 重载构造函数
    ///
    /// - Parameter title: 标题
    init(title: String?) {
        super.init(frame: CGRect())
        // 1, 判断是否为nil, 并设置title和头像
        if title == nil {
            setTitle("首页", for: .normal)
        } else {
            // 设置title
            setTitle(title! + " ", for: .normal)
            // 设置图像
            setImage(UIImage(named: "navigationbar_arrow_down"), for: .normal)
            setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        }
        
        // 2,设置字体和颜色
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray, for: .normal)
        
        // 3,设置大小
        sizeToFit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    /// FIXME:该方法会被系统调用两次
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let titleLabel = titleLabel,
            let imageView = imageView
        else {
            return
        }
        
        /*
         该方法会被系统调用两次, 导致下面的写法不能使用
         print("移动前\(titleLabel)--\(imageView)")
        // 将label向左移动图像的宽度
        titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.width, dy: 0)
        // 将imageView向右移动title的宽度
        imageView.frame = imageView.frame.offsetBy(dx: titleLabel.bounds.width, dy: 0)
        print("移动后\(titleLabel)--\(imageView)")
        */
        
        let imageW = imageView.bounds.width
        let imageH = imageView.bounds.height
        let imageY = imageView.frame.origin.y
        let titleW = titleLabel.bounds.width
        let titleY = titleLabel.frame.origin.y
        let titleH = titleLabel.bounds.height
        
        titleLabel.frame = CGRect(x: 0, y: titleY, width: titleW, height: titleH)
        imageView.frame = CGRect(x: titleW, y: imageY, width: imageW, height: imageH)
    }

}
